package com.msh.starter.redis.id;

import com.msh.frame.client.interfaces.IClassLoadLog;
import com.msh.frame.interfaces.IIdGenerateServiceId;
import com.msh.starter.redis.common.FastJson2JsonRedisSerializer;
import com.msh.starter.redis.config.RedisConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;


/**
 * 直接扫描优先注入
 * redis获取服务唯一id
 * 同时启动8个服务器能确保唯一(实际使用时最好减半)
 */
@Component
@ConditionalOnProperty(name = "msh.starter.idGenerate.service-id.redis.enable", havingValue = "true", matchIfMissing = true)
public class RedisIdGenerateServiceId implements IIdGenerateServiceId, IClassLoadLog {
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Value("${msh.starter.idGenerate.service-id.redis.biz:${spring.application.name}}")
    private String biz;
    private static final String REDIS_PREFIX = "msh:starter:id-generate:service-id:biz:";
    private int serviceId;

    @PostConstruct
    public void init(){
        Long increment = redisTemplate.opsForValue().increment(REDIS_PREFIX + biz, 1);
        serviceId =  (int) (increment%10);
        this.redisTemplate = null;
    }


    @Override
    public int serverId() {
        return serviceId;
    }

    @Override
    public int digit() {
        return 10;
    }

    @Override
    public int bit() {
        return 3;
    }

    @Override
    public String logInfo() {
        return "----执行类 " +
                RedisIdGenerateServiceId.class +
                "\r\n" +
                "--------加载类 " +
                RedisIdGenerateServiceId.class +
                "(IIdGenerateServiceId)\r\n";
    }
}
